//
//  NSOpenPanelExtension.swift
//  JKTools
//
//  Created by 姜奎 on 2024/4/26.
//

import Cocoa

extension NSOpenPanel {
    static func open(message: String? = nil, completion:@escaping (URL?)->Void) {
        open(directoryURL: FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first, message: message, completion: completion)
    }

    static func open(directoryURL: URL?, message: String? = nil, completion:@escaping (URL?)->Void) {

        guard let path = directoryURL?.path() else { return }
        if let bookmarkData = UserDefaults.readBookmarkData(by: directoryURL) {

            _ = bookmarkData.startAccessingSecurityScopedResource()
            completion(bookmarkData)
            bookmarkData.stopAccessingSecurityScopedResource()
            return
        }


        let panel = NSOpenPanel()

        panel.directoryURL = directoryURL
        panel.canChooseDirectories = true
        panel.canCreateDirectories = true
        panel.canChooseFiles = true
        panel.canSelectHiddenExtension = true
        panel.message = message ?? "如果路径不存在，请手动创建[\(path)]。"

        panel.begin { resp in
            guard resp == .OK else {
                return
            }
            completion(UserDefaults.writeBookmarkData(by: panel.url))
        }
    }
}
